<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>点亮星星</title>
  <style>
    body,
    ul,
    li {
      margin: 0;
      padding: 0;
    }

    li {
      list-style: none;
    }

    .rating {
      width: 300px;
      height: 50px;
      margin: 100px auto 10px;
    }

    .rating-item {
      float: left;
      width: 50px;
      height: 50px;
      background: url('images/start.png') no-repeat;
      background-size: 50px 100px;
      background-position: 0 -58px;
      overflow: hidden;
      margin-left: 10px;
    }

    p {
      width: 100px;
      height: 40px;
      line-height: 40px;
      font-size: 20px;
      margin: 0 auto;
    }
  </style>
</head>

<body>
  <ul class="rating" id="rating">
    <li class="rating-item" title="很不好"></li>
    <li class="rating-item" title="不好"></li>
    <li class="rating-item" title="一般"></li>
    <li class="rating-item" title="好"></li>
    <li class="rating-item" title="很好"></li>
  </ul>
  <p></p>

  <script src="js/jquery.1.12.4.js"></script>
  <script>
    // 默认点亮个数
    let num = 0;
    const $item = $('.rating').find('.rating-item');
    // 初始化。默认点亮一颗
    light(num);

    //
    $item.on('mouseover', function () {
      light($(this).index() + 1);
    }).on('click', function () {
      light($(this).index() + 1);
      $('p').text($(this).attr('title'));
      num = $(this).index() + 1;
    });
    $('#rating').on('mouseout', function () {
      light(num);
    });

    // 点亮星星的函数
    function light(num) {
      $item.each(function (index) {
        if (index < num) {
          // 点亮
          $(this).css('background-position', '0 0');
        } else {
          // 未亮
          $(this).css('background-position', '0 -58px');
        }
      })
    };
  </script>
</body>

</html>